package cn.edu.sdu.sol.intake_system.service;

import cn.edu.sdu.sol.intake_system.model.po.AdminInf;
import cn.edu.sdu.sol.intake_system.model.po.SysUser;
import cn.edu.sdu.sol.intake_system.model.po.UserType;
import cn.edu.sdu.sol.intake_system.model.vo.DataRequest;
import cn.edu.sdu.sol.intake_system.model.vo.DataResponse;
import cn.edu.sdu.sol.intake_system.repository.UserRepository;
import cn.edu.sdu.sol.intake_system.utils.VO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SuperAdminService {

    VO vo = new VO();
    @Autowired
    UserRepository userRepository;

    public DataResponse getAdminList() {
        List<SysUser> users = userRepository.findAdmin();
        List<Map> result = new ArrayList<>();
        for(SysUser user: users){
            String name = user.getName();
            String studentNum = user.getStudentNum();
            Integer personId = user.getUserPk();
            String position = "未知";
            AdminInf adminInf = user.getAdminInf();
            if(adminInf != null){
                position = adminInf.getPosition();
            }
            Map<String, Object> map = new HashMap<>();
            map.put("personName", name);
            map.put("studentNum", studentNum);
            map.put("position", position);
            map.put("personId", personId);
            result.add(map);
        }
        return vo.data(result);
    }

    public DataResponse deleteAdmin(DataRequest req) {
        Integer personId = req.getInteger("personId");
        //System.out.println(personId);
        Optional<SysUser> optionalSysUser = userRepository.findUserByUserPk(personId);
        if(optionalSysUser.isEmpty()){
            return vo.messageError("no such admin!");
        }
        SysUser user = optionalSysUser.get();
        if(user.getRole() == UserType.SUPER){
            return vo.messageError("不能修改超级管理员的权限!");
        }
        user.setRole(UserType.COMMON);
        userRepository.saveAndFlush(user);
        return vo.messageOK(user.getName()+"的权限已设为普通用户!");
    }

    public DataResponse addAdmin(DataRequest req) {
        String studentNum = req.getString("studentNum");
        Optional<SysUser> optionalSysUser = userRepository.findUserByStudentNum(studentNum);
        if(optionalSysUser.isEmpty()){
            return vo.messageError("no such user!");
        }
        SysUser user = optionalSysUser.get();
        if(user.getRole() == UserType.SUPER){
            return vo.messageError("不能修改超级管理员的权限!");
        }
        user.setRole(UserType.ADMIN);
        userRepository.saveAndFlush(user);
        return vo.messageOK(user.getName()+"的权限已设为管理员!");
    }
}
